package cn.raven.basic.controller;

import cn.raven.basic.annotation.PreAuthorize;
import cn.raven.basic.utils.AjaxResult;
import cn.raven.basic.utils.FastdfsUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    @PostMapping
    public AjaxResult upload(@RequestPart(value = "file") MultipartFile file){
        try {
            //获取byte[] 数组
            byte[] bytes = file.getBytes();
            //通过工具类获取文件后缀
            String fileName = FilenameUtils.getExtension(file.getOriginalFilename());
            String path = FastdfsUtil.upload(bytes, fileName);
            return AjaxResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙,上传失败");
        }
    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "path") String path){
        try {
            // /group1/M00/00/5C/CgAIC2K-xf-AKFCxAAGMtIYV7E4729.jpg
            //从下标1开始截取 group1/M00/00/5C/CgAIC2K-xf-AKFCxAAGMtIYV7E4729.jpg
            String pathT = path.substring(1);
            // 从下标0截取第一个/出现的位置 含头不含尾  group1
            String group = pathT.substring(0, pathT.indexOf("/"));
            String fileName = pathT.substring(pathT.indexOf("/") + 1);
            FastdfsUtil.delete(group,fileName);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统错误,上传失败");
        }
    }
}
